package multithreaded;

// 模拟售票的线程安全问题
public class ThreadTest3 {

    public static void main(String[] args) {
        Ticket ticket = new Ticket();

        Thread t1 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 40; i++) {
                    ticket.saleTicket();
                }
            }
        }, "线程1：");
        Thread t2 = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 60; i++) {
                    ticket.saleTicket();
                }
            }
        }, "线程2：");

        t1.start();
        t2.start();
    }

}

// 资源类
class Ticket {
    private int number = 100;

    public /*synchronized*/  /*同步方法*/ void saleTicket() {

        synchronized (this) { /*同步代码块*/
            if (number > 0) {
                System.out.println(Thread.currentThread().getName() + "卖出第" + number-- + "张票");

            }
        }

    }
}


